﻿using Cxuu.Common;
using Cxuu.Models;
using Microsoft.Extensions.DependencyInjection;
using PetaPoco;
using System.Threading.Tasks;

namespace Cxuu.Repository
{
    [UseDI(ServiceLifetime.Scoped)]
    public class NoticeKeyRepository : BaseRepository<NoticeKey, PetaPocoContext>
    {
        public NoticeKeyRepository(PetaPocoContext petaPocoContext) : base(petaPocoContext) { }


        public virtual async Task<int> CountAsync(int uid)
        {
            if (uid == 0)
                return await CreateDAO().ExecuteScalarAsync<int>("select COUNT(Status) from cxuu_notice_key where Status = 0");
            else
                return await CreateDAO().ExecuteScalarAsync<int>("select COUNT(Status) from cxuu_notice_key where Status = 0 and GetUid = @0", uid);
        }

        public async Task<Page<ViewNotice>> GetPageListAsync(string keyword, int page, int limit, int uid, int? status, int geted)
        {
            Sql sql = Sql.Builder;
            sql.Select("A.Id,A.GetUid,A.ReadTime,A.Status,B.Username,B.Nickname,C.Nickname as PostNickname,C.Username as Postname,D.Title,D.Content,D.Type,D.PostUid,D.PostTime,D.Id as NoticeId")
                .From("cxuu_notice_key as A")
                .LeftJoin("cxuu_notice as D").On("A.Nid = D.Id")
                .LeftJoin("cxuu_admin_user as B").On("A.GetUid = B.Id");
            sql.LeftJoin("cxuu_admin_user as C").On("D.PostUid = C.Id");

            if (!string.IsNullOrEmpty(keyword))
                sql.Where("D.Title like @0", "%" + keyword + "%");

            if (status != null)
                sql.Where("A.Status = @0", status);

            if (geted == 1)
            {
                sql.Where("D.PostUid =@0", uid);
            }
            else if (uid != 0)
                sql.Where("A.GetUid = @0", uid);

            sql.OrderBy("A.Status asc,A.Id desc");
            return await CreateDAO().PageAsync<ViewNotice>(page, limit, sql);
        }
    }
}
